const Koa = require('koa');
const path = require('path');
const logger = require('koa-morgan');
const FileStreamRotator = require('file-stream-rotator');
const koaStatic = require('koa-static');
const info = require('debug')('log:info');
const error = require('debug')('log:error');
const app = new Koa();
const config = require('./config');
module.exports = app;
var runing = process.env.RUN_CONF;
// 异常捕获
app.use(async (ctx,next)=>{
  try{
    await next();
  }catch(e){
    ctx.response.status = 500;
    ctx.response.body = e;
    error(e);
  }
})



//访问日志
const logDirectory = path.join(__dirname,'logs');
// fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
var accessLogStream = FileStreamRotator.getStream({
  filename: logDirectory + '/access-%DATE%.log',
  frequency: 'daily',
  verbose: false
});
app.use(logger('combined', {stream: accessLogStream}));

// 运行日志中间件
var runningLogStream = FileStreamRotator.getStream({
  filename: logDirectory + '/running-%DATE%.log',
  frequency: 'daily',
  verbose: false
});
app.use( (ctx,next)=>{
    ctx.log=(content,level='info')=>{
      let time = new Date().toLocaleString();
      let w = `[${level}][${time}]:${content}`;
      runningLogStream.write(w+'\n');
      info(w);
    }
    return next();
});
// 静态资源
app.use(koaStatic(
  path.join( __dirname,  'build')
))
// 使用ctx.body解析中间件
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())
// 模板、视图
const render = require('koa-art-template');
render(app, {
  root: path.join(__dirname, 'src/views'),
  extname: '.html',
  debug: config[runing].debug
});
// 路由
const router = require('./src/routes');
app.use(router.routes())
